package sqlx

import (
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	gormlogger "gorm.io/gorm/logger"
	"os"
	"time"
)

func NewPgsql(datasource string, opt ...Option) *gorm.DB {
	opts := newDefaultOptions()
	for _, o := range opt {
		o(opts)
	}

	db, err := gorm.Open(postgres.Open(datasource), &gorm.Config{
		Logger: NewLogger(Config{
			SlowThreshold:             200 * time.Millisecond,
			LogLevel:                  gormlogger.Warn,
			IgnoreRecordNotFoundError: true,
			Colorful:                  false,
		}),
	})
	if err != nil {
		logx.Errorf("initialize db session failed: %v", err)
		os.Exit(1)
		return nil
	}
	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(opts.MaxIdleConn)
	sqlDB.SetMaxOpenConns(opts.MaxOpenConn)
	sqlDB.SetConnMaxLifetime(opts.MaxLifetime)
	return db
}
